﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 上位机Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            text_Serial_port();
            Initialization();
        }

        private void Initialization()
        {
            comboBox2.Text = "1";
            comboBox3.Text = "8";
            comboBox4.Text = "115200";
            comboBox5.Text = "奇校验";
        }

        private void text_Serial_port()
        {
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            for (int i = 0; i < ports.Length; i++)
            {
                comboBox1.Items.Add(ports[i]);
            }
            comboBox1.SelectedIndex = comboBox1.Items.Count > 0 ? 0 : -1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "打开串口")
            {
                try
                {
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = int.Parse(comboBox4.Text);
                    serialPort1.DataBits = int.Parse(comboBox3.Text);

                    if (comboBox2.Text == "1")
                    {
                        serialPort1.StopBits = System.IO.Ports.StopBits.One;
                    }
                    else if (comboBox2.Text == "1.5"){
                        serialPort1.StopBits = System.IO.Ports.StopBits.OnePointFive;

                    }
                    else if(comboBox2.Text=="2")
                    {
                        serialPort1.StopBits = System.IO.Ports.StopBits.Two;
                    }

                    if (comboBox5.Text == "无")
                    {
                        serialPort1.Parity = System.IO.Ports.Parity.None;
                    }
                    else if (comboBox5.Text == "奇校验")
                    {
                        serialPort1.Parity = System.IO.Ports.Parity.Odd;
                    }
                    else
                    {
                        serialPort1.Parity = System.IO.Ports.Parity.Even;

                    }
                    serialPort1.Open();
                    button1.Text = "关闭串口";
                }catch(Exception ex)
                {
                    MessageBox.Show("打开失败！\n错误信息:" + ex.Message, "提示");
                }
            }
            else
            {
                //关闭串口
                try
                {
                    serialPort1.Close();
                }
                catch(Exception )
                {

                }
                button1.Text = "打开串口";
            }
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int len = serialPort1.BytesToRead;
            byte[] buff = new byte[len];
            serialPort1.Read(buff, 0, len);
            string zixusonResult = Encoding.Default.GetString(buff);
            this.Invoke(new Action(() =>
            {
                if (checkBox1.Checked)
                {
                    textBox1.AppendText("" +byteToHexstr(buff));
                }
                else
                {
                    textBox1.AppendText("" + zixusonResult);
                }
                
            }));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

        private string byteToHexstr(byte[] buff)
        {
            string str = "";
            try
            {
                if (buff != null)
                {
                    for(int i = 0; i < buff.Length; i++)
                    {
                        str += buff[i].ToString("x2");
                        str += " ";
                    }
                }
            }
            catch (Exception) { return str; }
            return str;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            textBox2.Clear();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                send_mes();
            });
        }
        string _data;
        private void send_mes()
        {
            _data = textBox2.Text.ToString();
            try
            {
                if (_data.Length != 0)
                {
                    _data += " ";
                    if (checkBox2.Checked)
                    {
                        serialPort1.Write(Encoding.Default.GetString(strToHexbytes(_data)));
                    }
                    else
                    {
                        serialPort1.Write(_data);
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private byte[] strToHexbytes(string str)
        {
            str = str.Replace(" ", "");
            byte[] buff;
            if ((str.Length % 2) != 0)
            {
                buff = new byte[(str.Length + 1) / 2];
                try
                {
                    for (int i = 0; i < buff.Length; i++) {
                        buff[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
                    }
                    buff[buff.Length - 1] = Convert.ToByte(str.Substring(str.Length - 1, 1).PadLeft(2, '0'), 16);
                    return buff;

                }
                catch(Exception err)
                {
                    MessageBox.Show("含有非法的16进制的字符", "提示");
                    return null;

                }
            }
            else
            {
                buff = new byte[str.Length / 2];
                try
                {
                    for (int i = 0; i < buff.Length; i++)
                    {
                        buff[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show("含有非法的16进制的字符", "提示");
                    return null;

                }
            }
            return buff;
        }
    }
}
